package com.midele.goodstuff.data.repository

import com.midele.goodstuff.MainApplication
import com.midele.goodstuff.data.model.TouristUserBean
import com.midele.goodstuff.data.model.UserInfoBean
import com.midele.goodstuff.data.repository.net_util.ApiService
import com.midele.goodstuff.data.repository.net_util.NetworkConfig
import com.midele.goodstuff.data.repository.net_util.NetworkResult
import com.midele.goodstuff.data.repository.net_util.toApiFlow
import com.midele.goodstuff.util.DataStoreUtils
import com.midele.goodstuff.util.GsonUtils
import kotlinx.coroutines.flow.Flow
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody


class UserRepository() {

    private val apiService = NetworkConfig.createService(ApiService::class.java)

    val POST_REQUEST_JSON_TYPE: MediaType? = "application/json; charset=utf-8".toMediaTypeOrNull()

    /**
     * 注册
     */
    suspend fun register(deviceId: String,deviceIp:String): Flow<NetworkResult<TouristUserBean>> {
        val params: Map<String, String> = mapOf("deviceId" to deviceId, "osType" to "Android","appName" to "流溪","deviceIp" to deviceIp)
        val content = GsonUtils.toJson(params)
        val requestBody: RequestBody = content.toRequestBody(POST_REQUEST_JSON_TYPE)
        return apiService.register(requestBody).toApiFlow()
    }

    /**
     * 获取验证码
     */
    suspend fun sendValidateCode(phone: String): Flow<NetworkResult<Any>> {
        return apiService.sendValidateCode(phone).toApiFlow()
    }

    /**
     * 登录
     */
    suspend fun login(phone: String, code: String): Flow<NetworkResult<UserInfoBean>> {

        val deviceId =
            DataStoreUtils.readDataBlocking(MainApplication.instance, DataStoreUtils.PrefKeys.DEVICE_ID, "")

        val params: Map<String, String> =
            mapOf("deviceId" to deviceId, "osType" to "Android", "phone" to phone, "code" to code)
        val content = GsonUtils.toJson(params)
        val requestBody: RequestBody = content.toRequestBody(POST_REQUEST_JSON_TYPE)
        return apiService.login(requestBody).toApiFlow()
    }

    /**
     * 获取用户信息
     */
    suspend fun loadUserBaseInfo(): Flow<NetworkResult<UserInfoBean>> {
        return apiService.loadUserBaseInfo().toApiFlow()
    }

    /**
     * 退出账号
     */
    suspend fun logOut(): Flow<NetworkResult<Any>> {
        return apiService.logOut().toApiFlow()
    }

    /**
     * 注销账号
     */
    suspend fun invalidUserBase(): Flow<NetworkResult<Any>> {
        val userId =
            DataStoreUtils.readDataBlocking(MainApplication.instance, DataStoreUtils.PrefKeys.USER_ID, 0)
        return apiService.invalidUserBase(userId).toApiFlow()
    }

}